package com.heima.home.interceptor;



import com.auth0.jwt.interfaces.DecodedJWT;
import com.heima.home.util.JwtUtil;
import com.heima.home.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 在Controller方法执行之前被调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("AuthInterceptor拦截到的请求: {} {}", request.getMethod(), requestURI);

        // 1. 从请求头中获取 token (约定格式为 "Bearer token")
        String authHeader = request.getHeader("Authorization");

        // 2. 检查凭证是否存在且格式正确
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            // 如果没有token，设置401 Unauthorized状态码，并返回false，中断请求
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"message\": \"Missing or invalid token\"}"); // 可选：返回更详细的错误信息
            return false;
        }

        String token = authHeader.substring(7); // 去掉 "Bearer " 前缀，获取真正的token

        try {
            // 3. 验证 token
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);

            // 4. 验证通过，将解析出的用户信息存放到 ThreadLocal 中
            Integer userId = decodedJWT.getClaim("userId").asInt();
            Integer userType = decodedJWT.getClaim("userType").asInt();
            UserContext.setCurrentUser(userId, userType);

            // 5. 放行，让请求继续访问 Controller
            return true;
        } catch (Exception e) {
            // Token 验证失败（如过期、签名错误），同样返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"message\": \"Token verification failed: " + e.getMessage() + "\"}");
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完毕后，必须清除ThreadLocal中的用户信息，防止内存泄漏
        UserContext.clear();
    }
}